
/**
** \file       and_or.c
**
** \brief      this function parse the and_or rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse, De Olivera
**             Guillaume and Nguyen Viet Dung
**
** \version    1.0
**
** \date       28 Novembre 2010
**
*/

#include "rules.h"

static int              init1(struct andor              *andor)
{
  if (andor != NULL)
    andor->pl = calloc(1, sizeof (s_pipeline));

  return (0);
}

static void             init2(struct andor              *andor)
{
  if (andor != NULL)
  {
    if (andor->next == NULL)
      andor->next = calloc(1, sizeof (s_andor));
  }
}
static s_pipeline       *init3(s_pipeline                *pipe,
                               struct andor             *andor)
{
  s_pipeline            *tmp_pipe = NULL;

  if (andor == NULL)
    return (NULL);

  tmp_pipe = andor->pl;

  if (pipe == NULL)
  {
    pipe = calloc(1, sizeof (s_pipeline));

    if (tmp_pipe != NULL)
    {
      while (tmp_pipe != NULL && tmp_pipe->next != NULL)
        tmp_pipe = tmp_pipe->next;

      tmp_pipe->next = pipe;
      return (pipe);
    }

    free(pipe);
    pipe = NULL;
  }

  return (pipe);
}

static void             *aux_free(struct andor          *andor)
{
  free(andor->next->pl);
  andor->next->pl = NULL;
  free(andor->next);
  andor->next = NULL;
  return (NULL);
}

struct andor            *rule_and_or(struct andor       *andor)
{
  s_pipeline            *tmp_pipe = NULL;

  if (!(init1(andor)) && g_data->lexer != NULL && (rule_pipeline(andor->pl)))
  {
    tmp_pipe = andor->pl->next;

    while ((g_data->lexer != NULL) &&
           (strcmp(g_data->lexer->token->id, "&&") == 0
            || strcmp(g_data->lexer->token->id, "||") == 0))
    {
      andor->and_or = malloc(sizeof (char) * 3);
      andor->and_or = strcpy(andor->and_or, g_data->lexer->token->id);

      g_data->lexer = g_data->lexer->next;

      while (g_data->lexer != NULL
	     && strcmp(g_data->lexer->token->id, "\n") == 0)
        g_data->lexer = g_data->lexer->next;

      if (rule_pipeline((tmp_pipe = init3(tmp_pipe, andor))) == NULL)
        return (aux_free(andor));

      tmp_pipe = tmp_pipe->next;
    }

    init2(andor);
    return (andor);
  }

  free(andor->pl);
  andor->pl = NULL;
  return (NULL);
}
